package cn.stylefeng.guns.modular.system.controller.webController;

import cn.hutool.core.bean.BeanUtil;
import cn.stylefeng.guns.core.common.exception.BizExceptionEnum;
import cn.stylefeng.guns.core.util.WeixinConfig;
import cn.stylefeng.guns.core.util.XmlUtils;
import cn.stylefeng.guns.modular.system.entity.*;
import cn.stylefeng.guns.modular.system.service.*;
import cn.stylefeng.roses.core.base.controller.BaseController;
import cn.stylefeng.roses.core.reqres.response.ResponseData;
import cn.stylefeng.roses.core.util.ToolUtil;
import cn.stylefeng.roses.kernel.model.exception.ServiceException;
import com.alibaba.fastjson.JSONArray;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang.RandomStringUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedOutputStream;
import java.io.IOException;
import java.time.LocalDateTime;
import java.util.*;
import java.util.concurrent.TimeUnit;

/**
 * ClassName:    ExamController
 * Package:    cn.stylefeng.guns.modular.system.controller.webController
 * Description:
 * Datetime:    2020/8/10   14:40
 */
@Api(value = "考试管理接口", tags = "ExamApiController", description = "考试管理接口")
@AllArgsConstructor
@RestController
@RequestMapping("/api/exam")
public class ExamApiController extends BaseController {


    /**
     * 微信支付回调   返回成功xml
     */
    final private String resSuccessXml = "<xml><return_code><![CDATA[SUCCESS]]></return_code><return_msg><![CDATA[OK]]></return_msg></xml>";

    /**
     * 微信支付回调   返回失败xml
     */
    final private String resFailXml = "<xml><return_code><![CDATA[FAIL]]></return_code><return_msg><![CDATA[报文为空]]></return_msg></xml>";

    private ExamService examService;
    private ExamContentService examContentService;
    private ExamUserService examUserService;
    private ExamResultUserService examResultUserService;
    private ExamMonthService examMonthService;
    private ExamPlaceService examPlaceService;
    private ExamPlaceClassService examPlaceClassService;
    private SchoolRelationMonthService schoolRelationMonthService;
    private SysUserProfitService userProfitService;
    private SysUserProfitLogService profitLogService;
    private SysUserProfitExtractLogService extractLogService;
    private WeChatPayService weChatPayService;
    private RedisTemplate redisTemplate;

    @ApiOperation(value = "创建考试月份", notes="创建考试月份")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "examMonthId", value = "ID", paramType = "query"),
            @ApiImplicitParam(name = "month", value = "月份", paramType = "query",required = true),
            @ApiImplicitParam(name = "createUser", value = "创建人", paramType = "query",required = true),
            @ApiImplicitParam(name = "soldOut", value = "上架下架（0、下架，1、上架）", paramType = "query",required = true),
    })
    @RequestMapping(value = "/examMonthSave",method = RequestMethod.POST, produces = "application/json")
    public ResponseData examMonthSave (ExamMonth examMonth){
        examMonth.setCreateTime(LocalDateTime.now());
        examMonth.setEffective(1);
        examMonthService.saveOrUpdate(examMonth);
        return SUCCESS_TIP;
    }
    @ApiOperation(value = "获取考试月份", notes="获取考试月份")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "createUsers", value = "创建人ID(多个逗号隔开)", paramType = "query"),
            @ApiImplicitParam(name = "examMonthIds", value = "主键ID(多个逗号隔开)", paramType = "query"),
            @ApiImplicitParam(name = "soldOut", value = "上架下架（0、下架，1、上架）", paramType = "query"),
    })
    @RequestMapping(value = "/getExamMonth",method = RequestMethod.POST, produces = "application/json")
    public ResponseData getExamMonth (@RequestParam(value = "createUsers",required = false) String createUsers,
                                      @RequestParam(value = "examMonthIds",required = false) String examMonthIds,
                                      @RequestParam(value = "soldOut",required = false) Integer soldOut){
        QueryWrapper<ExamMonth> wrapper = new QueryWrapper<ExamMonth>().eq("effective", 1);
        if(ToolUtil.isNotEmpty(createUsers)){
            wrapper.in("create_user", createUsers.split(","));
        }
        if(ToolUtil.isNotEmpty(examMonthIds)){
            wrapper.in("exam_month_id", examMonthIds.split(","));
        }
        if(ToolUtil.isNotEmpty(soldOut)){
            wrapper.eq("sold_out", soldOut);
        }
        return ResponseData.success(examMonthService.list(wrapper));
    }

    @ApiOperation(value = "学校关联考试月份", notes="学校关联考试月份")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "schoolUserId", value = "学校ID", paramType = "query",required = true),
            @ApiImplicitParam(name = "examMonthIds", value = "考试月份ID（多个逗号隔开）", paramType = "query",required = true),
    })
    @RequestMapping(value = "/schoolRelationMonth",method = RequestMethod.POST, produces = "application/json")
    public ResponseData schoolRelationMonth (@RequestParam(value = "schoolUserId") Long schoolUserId,
                                             @RequestParam(value = "examMonthIds") String examMonthIds){
        schoolRelationMonthService.remove(new QueryWrapper<SchoolRelationMonth>().eq("school_user_id",schoolUserId));
        schoolRelationMonthService.add(schoolUserId,examMonthIds);
        return SUCCESS_TIP;
    }
    @ApiOperation(value = "获取学校关联考试月份", notes="获取学校关联考试月份")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "schoolUserId", value = "学校ID", paramType = "query",required = true),
    })
    @RequestMapping(value = "/getSchoolRelationMonth",method = RequestMethod.POST, produces = "application/json")
    public ResponseData getSchoolRelationMonth (@RequestParam(value = "schoolUserId") Long schoolUserId){
        SchoolRelationMonth one = schoolRelationMonthService.
                getOne(new QueryWrapper<SchoolRelationMonth>().eq("school_user_id", schoolUserId));
        return ResponseData.success(one);
    }

    @ApiOperation(value = "删除考试月份", notes="删除考试月份")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "examMonthId", value = "考试月份ID", paramType = "query",required = true),
    })
    @RequestMapping(value = "/examMonthDelete",method = RequestMethod.POST, produces = "application/json")
    @ResponseBody
    public ResponseData examMonthDelete (@RequestParam(value = "examMonthId") Long examMonthId ){
        examMonthService.update(new ExamMonth(),
                new UpdateWrapper<ExamMonth>().set("effective",0).eq("exam_month_id",examMonthId));
        return SUCCESS_TIP;
    }

    @ApiOperation(value = "创建考试场地", notes="创建考试场地")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "examPlaceId", value = "ID", paramType = "query"),
            @ApiImplicitParam(name = "place", value = "地点", paramType = "query",required = true),
            @ApiImplicitParam(name = "createUser", value = "创建人", paramType = "query",required = true),
            @ApiImplicitParam(name = "soldOut", value = "上架下架（0、下架，1、上架）", paramType = "query",required = true),
            @ApiImplicitParam(name = "placeClass", value = "班级人数", paramType = "query",required = true),

    })
    @RequestMapping(value = "/examPlaceSave",method = RequestMethod.POST, produces = "application/json")
    public ResponseData examPlaceSave (ExamPlace examPlace,
                                       @RequestParam(value = "placeClass") String placeClass){
        List<ExamPlaceClass> examPlaceClassList = JSONArray.parseArray(placeClass, ExamPlaceClass.class);
        examPlace.setCreateTime(LocalDateTime.now());
        examPlace.setEffective(1);
        examPlaceService.saveOrUpdate(examPlace);
        ExamPlace finalExamPlace = examPlaceService.getById(examPlace.getExamPlaceId());
        examPlaceClassList.forEach(examPlaceClass -> {
            BeanUtil.copyProperties(finalExamPlace,examPlaceClass);
            examPlaceClass.setPlaceClassResidueNum(examPlaceClass.getPlaceClassNum());
            examPlaceClassService.saveOrUpdate(examPlaceClass);
        });
        return SUCCESS_TIP;
    }

    @ApiOperation(value = "删除考试场地", notes="删除考试场地")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "examPlaceId", value = "ID", paramType = "query",required = true),
    })
    @RequestMapping(value = "/examPlaceDelete",method = RequestMethod.POST, produces = "application/json")
    public ResponseData examPlaceDelete (@RequestParam(value = "examPlaceId") Long examPlaceId){
        examPlaceService.update(new ExamPlace(),
                new UpdateWrapper<ExamPlace>().set("effective",0).eq("exam_place_id",examPlaceId));
        return SUCCESS_TIP;
    }

    @ApiOperation(value = "删除考试场地-班级人数", notes="删除考试场地-班级人数")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "examPlaceId", value = "ID", paramType = "query",required = true),
    })
    @RequestMapping(value = "/examPlaceClassDelete",method = RequestMethod.POST, produces = "application/json")
    @ResponseBody
    public ResponseData examPlaceClassDelete (@RequestParam(value = "examPlaceClassId") Long examPlaceClassId){
        examPlaceClassService.update(new ExamPlaceClass(),
                new UpdateWrapper<ExamPlaceClass>()
                        .set("effective",0).eq("exam_place_class_id",examPlaceClassId));
        return SUCCESS_TIP;
    }

    @ApiOperation(value = "获取考试场地", notes="获取考试场地")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "createUsers", value = "创建人ID(多个逗号隔开)", paramType = "query",required = true),
            @ApiImplicitParam(name = "soldOut", value = "上架下架（0、下架，1、上架）", paramType = "query"),
    })
    @RequestMapping(value = "/getExamPlace",method = RequestMethod.POST, produces = "application/json")
    public ResponseData getExamPlace (@RequestParam(value = "createUsers") String createUsers,
                                      @RequestParam(value = "soldOut",required = false) Integer soldOut){
        QueryWrapper<ExamPlace> wrapper = new QueryWrapper<ExamPlace>()
                .in("create_user", createUsers.split(",")).eq("effective", 1);
        if(ToolUtil.isNotEmpty(soldOut)){
            wrapper.eq("sold_out", soldOut);
        }
        return ResponseData.success(examPlaceService.list(wrapper));
    }
    @ApiOperation(value = "获取考试场地-班级人数", notes="获取考试场地-班级人数")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "examPlaceId", value = "examPlaceId", paramType = "query"),
            @ApiImplicitParam(name = "examPlaceClassId", value = "examPlaceClassId", paramType = "query"),
    })
    @RequestMapping(value = "/examPlaceClassList",method = RequestMethod.POST, produces = "application/json")
    @ResponseBody
    public ResponseData examPlaceClassList (@RequestParam(value = "examPlaceId",required = false) Long examPlaceId ,
                                            @RequestParam(value = "examPlaceClassId",required = false) Long examPlaceClassId ){
        QueryWrapper<ExamPlaceClass> wrapper = new QueryWrapper<ExamPlaceClass>().eq("effective", 1);
        if(ToolUtil.isNotEmpty(examPlaceId)){
            wrapper.eq("exam_place_id", examPlaceId);
        }
        if(ToolUtil.isNotEmpty(examPlaceClassId)){
            wrapper.eq("exam_place_class_id", examPlaceClassId);
        }
        return ResponseData.success(examPlaceClassService.list(wrapper));
    }


    @ApiOperation(value = "创建考试", notes="创建考试")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "examId", value = "examId", paramType = "query"),
            @ApiImplicitParam(name = "examTitle", value = "考试名称", paramType = "query",required = true),
            @ApiImplicitParam(name = "examMonthId", value = "考试月份", paramType = "query",required = true),
            @ApiImplicitParam(name = "examMajor", value = "考试专业", paramType = "query",required = true),
            @ApiImplicitParam(name = "examPlaceId", value = "考试地点", paramType = "query",required = true),
            @ApiImplicitParam(name = "examProvince", value = "省", paramType = "query",required = true),
            @ApiImplicitParam(name = "examCity", value = "市", paramType = "query",required = true),
            @ApiImplicitParam(name = "examCounty", value = "区县", paramType = "query",required = true),
            @ApiImplicitParam(name = "examAddress", value = "详细地址", paramType = "query",required = true),
            @ApiImplicitParam(name = "examContent", value = "考试内容", paramType = "query",required = true),
            @ApiImplicitParam(name = "examPlaceCost", value = "考点费", paramType = "query",required = true),
            @ApiImplicitParam(name = "examServiceCost", value = "考务费", paramType = "query",required = true),
            @ApiImplicitParam(name = "createUser", value = "创建人ID", paramType = "query",required = true),
            @ApiImplicitParam(name = "soldOut", value = "是否有效（0、无效，1、有效）", paramType = "query"),
            @ApiImplicitParam(name = "remarks", value = "备注", paramType = "query"),
    })
    @RequestMapping(value = "/examSave",method = RequestMethod.POST, produces = "application/json")
    public ResponseData examSave (Exam exam){
        examService.examSave(exam);
        return SUCCESS_TIP;
    }

    @ApiOperation(value = "考试列表", notes="考试列表")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "createUsers", value = "创建人ID(多个逗号隔开)", paramType = "query"),
            @ApiImplicitParam(name = "examMonthIds", value = "考试月份ID(多个逗号隔开)", paramType = "query"),
            @ApiImplicitParam(name = "examIds", value = "考试ID(多个逗号隔开)", paramType = "query"),
            @ApiImplicitParam(name = "soldOut", value = "上架下架（0、下架，1、上架）", paramType = "query"),
            @ApiImplicitParam(name = "userId", value = "userId", paramType = "query"),
    })
    @RequestMapping(value = "/examList",method = RequestMethod.POST, produces = "application/json")
    public ResponseData examList (@RequestParam(value = "createUsers",required = false) String createUsers,
                                  @RequestParam(value = "examMonthIds",required = false) String examMonthIds,
                                  @RequestParam(value = "soldOut",required = false) Integer soldOut,
                                  @RequestParam(value = "examIds",required = false) String examIds,
                                  @RequestParam(value = "userId",required = false) Long userId){
        return ResponseData.success(examService.examList(createUsers,examMonthIds,soldOut,examIds,userId));
    }

    private Boolean verifyExam (String examIds,Double price){
        Map<String, Object> map = examService.getMap(new QueryWrapper<Exam>()
                .select("SUM(exam_place_cost + exam_service_cost) examPrice")
                .in("exam_id", Arrays.asList(examIds.split(","))));
        return Optional.ofNullable(map).map(m->{
            double examPrice = Double.parseDouble(m.get("examPrice").toString());
            return Math.abs(examPrice-price)<(1e-6);
        }).orElseGet(()->false);
    }

    /**
     * 微信HttpClient请求，用于获取access_token等，
     * @param url
     * @param json
     * @return
     */
    @ApiOperation(value = "微信HttpClient请求", notes="微信HttpClient请求，用于获取access_token等")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "url", value = "http请求url", paramType = "query", required = true),
            @ApiImplicitParam(name = "json", value = "json参数对象", paramType = "query"),
    })
    @RequestMapping(value = "/weChatHttpClient", method = RequestMethod.POST, produces = "application/json")
    @ResponseBody
    public ResponseData weChatHttpClient (@RequestParam(value = "url") String url,
                                          @RequestParam(value = "json") String json){
        return ResponseData.success(weChatPayService.weChatHttpClient(url,json));
    }

    @ApiOperation(value = "学生考试报名-微信预下单", notes="学生考试报名-微信预下单")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "examIds", value = "考试ID(多个逗号隔开)", paramType = "query",required = true),
            @ApiImplicitParam(name = "userIds", value = "学生ID（多个逗号隔开）", paramType = "query",required = true),
            @ApiImplicitParam(name = "createUser", value = "提交人", paramType = "query",required = true),
            @ApiImplicitParam(name = "price", value = "价格", paramType = "query",required = true),
            @ApiImplicitParam(name = "appid", value = "appid", paramType = "query",required = true),
            @ApiImplicitParam(name = "trade_type", value = "trade_type", paramType = "query",required = true),
            @ApiImplicitParam(name = "mchId", value = "mchId", paramType = "query",required = true),
            @ApiImplicitParam(name = "openid", value = "openid", paramType = "query"),
    })
    @Transactional
    @RequestMapping(value = "examUserPay", method = RequestMethod.POST, produces = "application/json")
    public ResponseData examUserPay (HttpServletRequest request,
                                     @RequestParam(value = "examIds") String examIds,
                                     @RequestParam(value = "userIds") String userIds,
                                     @RequestParam(value = "createUser") Long createUser,
                                     @RequestParam(value = "price") Double price,
                                     @RequestParam(value = "appid") String appid,
                                     @RequestParam(value = "trade_type") String trade_type,
                                     @RequestParam(value = "mchId") String mchId,
                                     @RequestParam(value = "openid",required = false) String openid){
        if("JSAPI".equals(trade_type) && ToolUtil.isEmpty(openid)){
            return ResponseData.error("缺少openid！");
        }
        if(!verifyExam(examIds,price)){
            return ResponseData.error("费用错误！");
        }
        String out_trade_no = System.currentTimeMillis() + "";
        Double money = price * 100;
        String nonceStr = DigestUtils.md5Hex(UUID.randomUUID() + RandomStringUtils.randomAlphabetic(30));
        String result = weChatPayService.getParameterMap(request,money,appid,trade_type,mchId,openid,nonceStr,out_trade_no);
        Map<String, String> resultMap = XmlUtils.toObject(result, new com.fasterxml.jackson.core.type.TypeReference<Map<String, String>>() {});

        String returnMsg = resultMap.get("return_msg");
        String resultCode = resultMap.get("result_code");
        if (StringUtils.equals(returnMsg, "OK") && StringUtils.equals(resultCode, "SUCCESS")) {
            //向redis存入订单数据 30分钟后过期
            redisTemplate.opsForHash().put("exam",out_trade_no,
                    "{userIds:"+userIds+",examIds:"+examIds+",createUser:"+createUser+"}");
            redisTemplate.expire(out_trade_no, 30, TimeUnit.MINUTES);
            return ResponseData.success(weChatPayService.getModelMap(money,appid,nonceStr,out_trade_no,resultMap));
        } else {
            return ResponseData.error(500, "订单错误", resultMap);
        }
    }

    /**
     * 微信APP支付结果通知
     *
     * @param request
     * @return
     */
    @Transactional(rollbackFor=Exception.class)
    @ResponseBody
    @RequestMapping("/weChatPay_notify")
    public void weChatPay_notify(HttpServletRequest request, HttpServletResponse response) throws IOException {
        String resXml = "";
        Map<String, String> params = weChatPayService.getParams(request, response);
        if (!WeixinConfig.isTenpaySign(params)) {
            System.out.println("===============微信验签失败==============");
            resXml = resFailXml;
        } else {
            System.out.println("===============付款成功==============");
            // 处理业务开始
            examUserService.userSignUp(params.get("out_trade_no"), params.get("transaction_id"), Double.parseDouble(params.get("total_fee")) / 100);
           // 收益业务
            userProfitService.add (params.get("out_trade_no"),Double.parseDouble(params.get("total_fee")) / 100);
            resXml = resSuccessXml;
        }
        try {
            // 处理业务完毕
            BufferedOutputStream out = new BufferedOutputStream(response.getOutputStream());
            out.write(resXml.getBytes());
            out.flush();
            out.close();
        } catch (IOException e) {
        }
    }

    @ApiOperation(value = "学生免费考试报名", notes="学生免费考试报名")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "examIds", value = "考试ID(多个逗号隔开)", paramType = "query",required = true),
            @ApiImplicitParam(name = "userIds", value = "学生ID（多个逗号隔开）", paramType = "query",required = true),
    })
    @Transactional
    @RequestMapping(value = "examUserGratisPay", method = RequestMethod.POST, produces = "application/json")
    public ResponseData examUserGratisPay (@RequestParam(value = "examIds") String examIds,
                                           @RequestParam(value = "userIds") String userIds){
        Arrays.asList(examIds.split(",")).forEach(examId->{
            Exam exam = examService.getById(examId);
            if (exam.getExamPlaceCost()>0 || exam.getExamServiceCost()>0){
                throw new ServiceException(BizExceptionEnum.REQUEST_NULL);
            }
            Arrays.asList(userIds.split(",")).forEach(userId->{
                examUserService.userSignUp(examId,userId);
            });
        });
        return SUCCESS_TIP;
    }

    @ApiOperation(value = "学生考试报名列表", notes="学生考试报名列表")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "userId", value = "学生ID", paramType = "query",required = true),
    })
    @RequestMapping(value = "examUserList", method = RequestMethod.POST, produces = "application/json")
    public ResponseData examUserList (@RequestParam(value = "userId") Long userId){
        Map<String, Object> map = examUserService.getMap(new QueryWrapper<ExamUser>()
                .select(" GROUP_CONCAT(exam_id) examIds").eq("user_id", userId));
        if(map.isEmpty()){
            return ResponseData.error("无数据！");
        }
        return ResponseData.success(examService
                .examList("","",1,map.get("examIds").toString(),userId));
    }

    @ApiOperation(value = "学生考试报名数据查询", notes="学生考试报名数据查询")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "examId", value = "考试ID", paramType = "query"),
            @ApiImplicitParam(name = "userId", value = "学生ID", paramType = "query"),
    })
    @RequestMapping(value = "examUserCens", method = RequestMethod.POST, produces = "application/json")
    public ResponseData examUserCens  (@RequestParam(value = "examId",required = false) Long examId,
                                       @RequestParam(value = "userId",required = false) Long userId){
        QueryWrapper<ExamUser> wrapper = new QueryWrapper<>();
        if(ToolUtil.isNotEmpty(examId)){
            wrapper.eq("exam_id",examId);
        }
        if(ToolUtil.isNotEmpty(userId)){
            wrapper.eq("user_id",userId);
        }
        return ResponseData.success(examUserService.list(wrapper));
    }

    @ApiOperation(value = "用户收益信息", notes="用户收益信息")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "userId", value = "用户ID", paramType = "query",required = true),
    })
    @RequestMapping(value = "userProfitInfo", method = RequestMethod.POST, produces = "application/json")
    public ResponseData userProfitInfo (@RequestParam(value = "userId") Long userId){
        return ResponseData.success(userProfitService.getUserProfit(userId));
    }

    @ApiOperation(value = "用户收益信息编辑", notes="用户收益信息编辑")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "userId", value = "用户ID", paramType = "query",required = true),
            @ApiImplicitParam(name = "userName", value = "转账人姓名", paramType = "query"),
            @ApiImplicitParam(name = "userAliAccount", value = "支付宝转账账号", paramType = "query"),
            @ApiImplicitParam(name = "state", value = "提现状态", paramType = "query"),
    })
    @RequestMapping(value = "userProfitEdit", method = RequestMethod.POST, produces = "application/json")
    public ResponseData userProfitEdit (@RequestParam(value = "userId") Long userId,
                                        @RequestParam(value = "userName",required = false) String userName,
                                        @RequestParam(value = "userAliAccount",required = false) String userAliAccount,
                                        @RequestParam(value = "state",required = false) Integer state){
        SysUserProfit profit = userProfitService.getUserProfit(userId);
        if(ToolUtil.isNotEmpty(state) && ( !profit.equals(1) || !profit.equals(2))){
            profit.setState(state);
        }
        if(ToolUtil.isNotEmpty(userName)){
            profit.setUserName(userName);
        }
        if(ToolUtil.isNotEmpty(userAliAccount)){
            profit.setUserAliAccount(userAliAccount);
        }
        userProfitService.updateById(profit);
        return SUCCESS_TIP;
    }

    @ApiOperation(value = "用户收益记录", notes="用户收益记录")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "userId", value = "用户ID", paramType = "query",required = true),
    })
    @RequestMapping(value = "profitLogList", method = RequestMethod.POST, produces = "application/json")
    public ResponseData profitLogList (@RequestParam(value = "userId") Long userId){
        return ResponseData.success(profitLogService.list(new QueryWrapper<SysUserProfitLog>().eq("user_id",userId)));
    }

    @ApiOperation(value = "用户收益提现记录", notes="用户收益提现记录")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "userId", value = "用户ID", paramType = "query",required = true),
    })
    @RequestMapping(value = "profitExtractLogList", method = RequestMethod.POST, produces = "application/json")
    public ResponseData profitExtractLogList (@RequestParam(value = "userId") Long userId){
        return ResponseData.success(extractLogService.list(
                new QueryWrapper<SysUserProfitExtractLog>().eq("user_id",userId)));
    }

    @ApiOperation(value = "根据考生号查询学生考试信息", notes="查询学生考试信息")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "studentCode", value = "考生号", paramType = "query"),
    })
    @RequestMapping(value = "getExamUserInfoByCode", method = RequestMethod.POST, produces = "application/json")
    public ResponseData getExamUserInfoByCode (@RequestParam(value = "studentCode") String studentCode){
        return ResponseData.success(examUserService.getExamUserInfoByCode(studentCode));
    }

    @ApiOperation(value = "根据考试ID查询考试内容", notes="根据考试ID查询考试内容")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "examId", value = "考试ID", paramType = "query"),
    })
    @RequestMapping(value = "getExamContentByExamId", method = RequestMethod.POST, produces = "application/json")
    public ResponseData getExamContentByExamId (@RequestParam(value = "examId") Long examId){
        return ResponseData.success(examContentService.list(new QueryWrapper<ExamContent>().eq("exam_id",examId)));
    }


    @ApiOperation(value = "成绩录入", notes="成绩录入")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "userId", value = "用户ID", paramType = "query",required = true),
            @ApiImplicitParam(name = "examUserId", value = "用户报名表ID", paramType = "query",required = true),
            @ApiImplicitParam(name = "examId", value = "考试ID", paramType = "query",required = true),
            @ApiImplicitParam(name = "examContentId", value = "考试内容ID", paramType = "query",required = true),
            @ApiImplicitParam(name = "examResult", value = "成绩", paramType = "query",required = true),
            @ApiImplicitParam(name = "examWork", value = "作品", paramType = "query",required = true),
    })
    @RequestMapping(value = "examResulSave", method = RequestMethod.POST, produces = "application/json")
    @ResponseBody
    public ResponseData examResulSave (ExamResultUser resultUser){
        examResultUserService.resultSave(resultUser);
        return SUCCESS_TIP;
    }

    @ApiOperation(value = "成绩列表", notes="成绩列表")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "name", value = "学生名称", paramType = "query"),
            @ApiImplicitParam(name = "createUser", value = "学校ID", paramType = "query")
    })
    @RequestMapping(value = "examResulList", method = RequestMethod.POST, produces = "application/json")
    @ResponseBody
    public ResponseData examResulList (@RequestParam(value = "name",required = false) String name ,
                                       @RequestParam(value = "createUser",required = false) Long createUser){
        List<Map<String, Object>> mapList = examUserService.examUser(name, createUser);
        mapList.forEach(map -> {
            map.put("examResultUserList",
                    examResultUserService.examResultUserList(Long.parseLong(map.get("user_id").toString()),
                            Long.parseLong(map.get("exam_id").toString())));
        });
        return ResponseData.success(mapList);
    }







}
